package demo;

import demo.service.vo.CertRequest;
import demo.service.vo.CertResponse;
import demo.thread.MakeCertThead;
import demo.thread.TaskInfo;
import demo.util.DataUtil;

import java.util.List;
import java.util.concurrent.*;

public class Main {

    public static void main(String[] args) {
        List<CertRequest> requestList = DataUtil.createCertRequest(1000);

        // 设置线程池参数
        int poolSize = 100;
        long keepAliveTime = 60L;
        int queueCapacity = 1000000;
        ExecutorService executor = new ThreadPoolExecutor(poolSize, poolSize,
                keepAliveTime, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(queueCapacity),
                new ThreadPoolExecutor.AbortPolicy());


        TaskInfo<CertResponse> taskInfo = new TaskInfo<>("task-1000", 1000);
        long t1 = System.currentTimeMillis();
        for (CertRequest request : requestList) {
            executor.execute(new MakeCertThead(request, taskInfo));
        }

        // 等待所有线程执行结束
        try {
            taskInfo.await();
            // 可设置 await 超时机制，达到超时强制停止 await
            //taskInfo.await(30, TimeUnit.SECONDS);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        // 关闭线程池
        executor.shutdown();

        long t2 = System.currentTimeMillis();

        System.out.println("FINISH!!! execute time=" + (t2 - t1));


        // 查看执行结果
        List<CertResponse> resultList = taskInfo.getResultList();
        System.out.println("result size=" + resultList.size());
        for(CertResponse response : resultList) {
            System.out.println(response.getId() + "-" + response.getSignCert());
        }

        System.exit(0);
    }

}
